package admin

import (
	"context"
	"errors"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/datatypes"
)

type RolePermissionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRolePermissionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RolePermissionLogic {
	return &RolePermissionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RolePermissionLogic) RolePermission(req *types.RolePermissionReq) (resp string, err error) {
	data := &models.AdminRole{}
	if !utils.GetDataById(req.RoleId, data) {
		return "", errors.New("角色不存在")
	}
	data.Permissions = datatypes.JSON(utils.StructToJson(req.Permissions))
	err = utils.UpdateByIdCols(req.RoleId, data, "permissions")
	if err != nil {
		logx.Errorf("更新角色权限失败: %v", err)
		return "", errors.New("更新角色权限失败")
	}
	return "操作成功", nil
}
